package edu.friday.common.security.service;

import edu.friday.common.exception.CustomException;
import edu.friday.common.exception.user.UserPasswordNotMatchException;
import edu.friday.common.result.RestResult;
import edu.friday.common.security.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Component
public class SysLoginService {
    @Autowired
    //不用自动导包
    private TokenService tokenService;
    @Resource
    private AuthenticationManager authenticationManager;

    //登录验证
    public String login(String username, String password, String code, String uuid) {
        Authentication authentication = null;
        try {
            authentication = authenticationManager.authenticate(
                    new UsernamePasswordAuthenticationToken(username, password));
        }
        catch (Exception e) {
            if (e instanceof BadCredentialsException) {
                throw new UserPasswordNotMatchException();
            }
            else {
                throw new CustomException(e.getMessage());
            }
        }
        LoginUser loginUser = (LoginUser)authentication.getPrincipal();
        return tokenService.createToken(loginUser);
    }
}
